package com.runvp.service.biz.handler;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.exception.base.BaseException;
import com.runvp.common.util.ToolUtils;
import com.runvp.common.utils.uuid.IdUtils;
import com.runvp.service.biz.domain.BizDeviceCargo;
import com.runvp.service.biz.service.IBizDeviceCargoService;
import com.runvp.service.out.OutUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Component
public class ClientOutHandler {

    @Autowired
    private IBizDeviceCargoService bizDeviceCargoService;


    /**
     * 充电
     *
     * @param sn
     * @param cargo
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean out(String sn, String cargo, String userId) {
        //查询端口信息
        BizDeviceCargo query = new BizDeviceCargo();
        query.setDeviceSn(sn);
        query.setNumber(ToolUtils.toInt(cargo));
        List<BizDeviceCargo> cargos = bizDeviceCargoService.selectBizDeviceCargoList(query);
        if (CollectionUtils.isEmpty(cargos)) {
            throw new BaseException("端口不存在或已禁用");
        }
        BizDeviceCargo deviceCargo = cargos.get(0);
        JSONObject param = new JSONObject();
        param.put("amt",1);
        param.put("po",deviceCargo.getNumber());
        param.put("oid", IdUtils.id());
        //执行充电
        if (OutUtil.out(sn, param.toJSONString())) {
            deviceCargo.setUpdateBy(userId);
            bizDeviceCargoService.updateBizDeviceCargo(deviceCargo);
        }
        return true;
    }

}
